<template>
  <div class="profile">
    <div class="profile-container">
      <!-- 个人信息卡片 -->
      <el-card class="profile-card">
        <template #header>
          <div class="card-header">
            <span>个人信息</span>
            <el-button type="primary" @click="editMode = !editMode">
              <el-icon><Edit /></el-icon>
              {{ editMode ? '取消编辑' : '编辑资料' }}
            </el-button>
          </div>
        </template>
        
        <div class="profile-content">
          <!-- 头像区域 -->
          <div class="avatar-section">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :disabled="!editMode"
            >
              <el-avatar :size="120" :src="userInfo.avatar">
                {{ userInfo.realName?.charAt(0) || userInfo.username?.charAt(0) }}
              </el-avatar>
              <div v-if="editMode" class="avatar-overlay">
                <el-icon><Camera /></el-icon>
                <span>更换头像</span>
              </div>
            </el-upload>
          </div>
          
          <!-- 基本信息 -->
          <div class="info-section">
            <el-form
              ref="profileFormRef"
              :model="formData"
              :rules="formRules"
              label-width="100px"
              :disabled="!editMode"
            >
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="formData.username" disabled />
                  </el-form-item>
                </el-col>
                
                <el-col :xs="24" :sm="12">
                  <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="formData.realName" placeholder="请输入真实姓名" />
                  </el-form-item>
                </el-col>
                
                <el-col :xs="24" :sm="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="formData.email" placeholder="请输入邮箱地址" />
                  </el-form-item>
                </el-col>
                
                <el-col :xs="24" :sm="12">
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="formData.phone" placeholder="请输入联系电话" />
                  </el-form-item>
                </el-col>
                
                <!-- 学生特有字段 -->
                <template v-if="userInfo.role === 'student'">
                  <el-col :xs="24" :sm="12">
                    <el-form-item label="学号" prop="studentId">
                      <el-input v-model="formData.studentId" placeholder="请输入学号" />
                    </el-form-item>
                  </el-col>
                  
                  <el-col :xs="24" :sm="12">
                    <el-form-item label="学院" prop="college">
                      <el-select v-model="formData.college" placeholder="请选择学院" style="width: 100%">
                        <el-option
                          v-for="college in colleges"
                          :key="college.value"
                          :label="college.label"
                          :value="college.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  
                  <el-col :xs="24" :sm="12">
                    <el-form-item label="专业" prop="major">
                      <el-input v-model="formData.major" placeholder="请输入专业" />
                    </el-form-item>
                  </el-col>
                  
                  <el-col :xs="24" :sm="12">
                    <el-form-item label="年级" prop="grade">
                      <el-select v-model="formData.grade" placeholder="请选择年级" style="width: 100%">
                        <el-option label="大一" value="1" />
                        <el-option label="大二" value="2" />
                        <el-option label="大三" value="3" />
                        <el-option label="大四" value="4" />
                        <el-option label="研一" value="5" />
                        <el-option label="研二" value="6" />
                        <el-option label="研三" value="7" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </template>
                
                <!-- 组织者特有字段 -->
                <template v-if="userInfo.role === 'organizer'">
                  <el-col :xs="24" :sm="12">
                    <el-form-item label="组织/部门" prop="organization">
                      <el-input v-model="formData.organization" placeholder="请输入所属组织或部门" />
                    </el-form-item>
                  </el-col>
                  
                  <el-col :xs="24" :sm="12">
                    <el-form-item label="职位" prop="position">
                      <el-input v-model="formData.position" placeholder="请输入职位" />
                    </el-form-item>
                  </el-col>
                </template>
                
                <el-col :xs="24">
                  <el-form-item label="个人简介" prop="bio">
                    <el-input
                      v-model="formData.bio"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入个人简介"
                      maxlength="500"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <div v-if="editMode" class="form-actions">
                <el-button type="primary" @click="saveProfile" :loading="saving">
                  <el-icon><Check /></el-icon>
                  保存修改
                </el-button>
                <el-button @click="cancelEdit">
                  <el-icon><Close /></el-icon>
                  取消
                </el-button>
              </div>
            </el-form>
          </div>
        </div>
      </el-card>
      
      <!-- 密码修改卡片 -->
      <el-card class="password-card">
        <template #header>
          <div class="card-header">
            <span>修改密码</span>
          </div>
        </template>
        
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
        >
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input
              v-model="passwordForm.currentPassword"
              type="password"
              placeholder="请输入当前密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="changePassword" :loading="changingPassword">
              <el-icon><Lock /></el-icon>
              修改密码
            </el-button>
            <el-button @click="resetPasswordForm">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 账户统计卡片 -->
      <el-card class="stats-card">
        <template #header>
          <div class="card-header">
            <span>账户统计</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :xs="12" :sm="6">
            <div class="stat-item">
              <div class="stat-number">{{ stats.totalActivities }}</div>
              <div class="stat-label">{{ userInfo.role === 'student' ? '参与活动' : '创建活动' }}</div>
            </div>
          </el-col>
          
          <el-col :xs="12" :sm="6">
            <div class="stat-item">
              <div class="stat-number">{{ stats.totalRegistrations }}</div>
              <div class="stat-label">{{ userInfo.role === 'student' ? '报名次数' : '收到报名' }}</div>
            </div>
          </el-col>
          
          <el-col :xs="12" :sm="6">
            <div class="stat-item">
              <div class="stat-number">{{ stats.totalFeedbacks }}</div>
              <div class="stat-label">{{ userInfo.role === 'student' ? '反馈次数' : '收到反馈' }}</div>
            </div>
          </el-col>
          
          <el-col :xs="12" :sm="6">
            <div class="stat-item">
              <div class="stat-number">{{ formatDate(userInfo.createdAt, 'YYYY-MM-DD') }}</div>
              <div class="stat-label">注册时间</div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils'
import api from '@/utils/api'
import {
  Edit,
  Camera,
  Check,
  Close,
  Lock,
  Refresh
} from '@element-plus/icons-vue'

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

const editMode = ref(false)
const saving = ref(false)
const changingPassword = ref(false)

const profileFormRef = ref()
const passwordFormRef = ref()

const uploadUrl = computed(() => `${api.defaults.baseURL}/upload/avatar`)

// 表单数据
const formData = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  studentId: '',
  college: '',
  major: '',
  grade: '',
  organization: '',
  position: '',
  bio: ''
})

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 统计数据
const stats = reactive({
  totalActivities: 0,
  totalRegistrations: 0,
  totalFeedbacks: 0
})

// 学院选项
const colleges = ref([
  { label: '计算机科学与技术学院', value: 'computer' },
  { label: '电子信息工程学院', value: 'electronic' },
  { label: '机械工程学院', value: 'mechanical' },
  { label: '经济管理学院', value: 'economics' },
  { label: '外国语学院', value: 'foreign' },
  { label: '艺术设计学院', value: 'art' },
  { label: '理学院', value: 'science' },
  { label: '文学院', value: 'literature' }
])

// 表单验证规则
const formRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  studentId: [
    { required: userInfo.value?.role === 'student', message: '请输入学号', trigger: 'blur' }
  ],
  college: [
    { required: userInfo.value?.role === 'student', message: '请选择学院', trigger: 'change' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 初始化表单数据
const initFormData = () => {
  const user = userInfo.value
  if (user) {
    Object.assign(formData, {
      username: user.username || '',
      realName: user.realName || '',
      email: user.email || '',
      phone: user.phone || '',
      studentId: user.studentId || '',
      college: user.college || '',
      major: user.major || '',
      grade: user.grade || '',
      organization: user.organization || '',
      position: user.position || '',
      bio: user.bio || ''
    })
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await api.get('/user/stats')
    Object.assign(stats, response.data.data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isJPG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 头像上传成功
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    userStore.updateUserInfo({ avatar: response.data.url })
    ElMessage.success('头像更新成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 保存个人资料
const saveProfile = async () => {
  try {
    await profileFormRef.value.validate()
    
    saving.value = true
    const response = await api.put('/user/profile', formData)
    
    if (response.data.code === 200) {
      await userStore.updateUserInfo(formData)
      editMode.value = false
      ElMessage.success('个人资料更新成功')
    } else {
      ElMessage.error(response.data.message || '更新失败')
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('更新失败，请重试')
    }
  } finally {
    saving.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  editMode.value = false
  initFormData()
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    changingPassword.value = true
    const response = await api.put('/user/password', {
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (response.data.code === 200) {
      resetPasswordForm()
      ElMessage.success('密码修改成功')
    } else {
      ElMessage.error(response.data.message || '密码修改失败')
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('密码修改失败，请重试')
    }
  } finally {
    changingPassword.value = false
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
}

onMounted(() => {
  initFormData()
  loadStats()
})
</script>

<style scoped>
.profile {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.profile-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.profile-card,
.password-card,
.stats-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.profile-content {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.avatar-section {
  flex-shrink: 0;
  text-align: center;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
}

.avatar-uploader:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
  font-size: 12px;
}

.info-section {
  flex: 1;
}

.form-actions {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.stat-item {
  text-align: center;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile {
    padding: 10px;
  }
  
  .profile-content {
    flex-direction: column;
    align-items: center;
    gap: 20px;
  }
  
  .avatar-section {
    width: 100%;
  }
  
  .info-section {
    width: 100%;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .form-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .stat-item {
    margin-bottom: 10px;
  }
  
  .stat-number {
    font-size: 20px;
  }
  
  .stat-label {
    font-size: 12px;
  }
}
</style>